package com.xf.oschina.view.book.factory;

import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Transformations;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.xf.oschina.module.story.domain.BookChapter;
import com.xf.oschina.module.story.domain.ChapterRead;
import com.xf.oschina.module.story.domain.Pager;
import com.xf.oschina.repository.EBookRepository;
import com.xf.oschina.utils.AbsentLiveData;
import com.xf.oschina.utils.DensityUtils;
import com.xf.oschina.utils.LogUtils;
import com.xf.oschina.utils.Resource;
import com.xf.oschina.utils.ScreenUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

public class LoadPager extends LoadPagerFactory {
    private int charpterNumber = 0;//章节数
    private static LoadPager instance;
    @Inject
    EBookRepository repository;
    protected MutableLiveData<Map<String, Object>> params = new MutableLiveData<>();
    private LiveData<Resource<Object>> charpter;
    private List<BookChapter.MixToc.Chapters> chapters;
    protected Map<String, Object> param = new HashMap<>();

    private LoadPager(Context context, float textSize) {
        rightMargin = topMargin = bottomMargin = DensityUtil.dp2px(20);
        leftMargin = DensityUtil.dp2px(15);
        mTextInterval = DensityUtils.sp2px(context, textSize) + DensityUtil.dp2px(2);
        mTitleInterval = DensityUtils.sp2px(context, textSize);
        screenHeight = ScreenUtils.getScreenHeight(context);
        screenWidth = ScreenUtils.getScreenWidth(context);
        contentHeight = (int) (screenHeight - 2 * topMargin);
        mVisibleHeight = contentHeight;
        mVisibleWidth = screenWidth - 2 * rightMargin;
        charpter = Transformations.switchMap(params, data -> {
            if (data == null)
                return AbsentLiveData.create();
            else
                return repository.loadDataNoDb(data, ChapterRead.class);
        });
        if (charpter != null)
            charpter.observe((LifecycleOwner) context, result -> {
                if (result != null && result.data instanceof ChapterRead) {
                    ChapterRead chapterRead= (ChapterRead) result.data;
                    ChapterRead.Chapter chapter = chapterRead.getChapter();
                }
            });
    }

    public static LoadPager getInstance(Context context, float textSize) {
        if (instance != null) {
            return instance;
        }
        return new LoadPager(context, textSize);
    }

    public void setChapters(List<BookChapter.MixToc.Chapters> chapters) {
        this.chapters = chapters;
    }

    @Override
    public String loadNextPager(int next) {
        if (pagers.size() < 3) {
            loadNextChapter();
        }
        return pagers.get(next).getContent();
    }

    private void loadNextChapter() {
        charpterNumber++;
        if (charpterNumber < chapters.size()) {
            String link = chapters.get(charpterNumber).getLink();
            param.put("url", link);
            params.setValue(param);
        }
    }

    private void loadForwardChapter() {

    }

    @Override
    public String loadForWardPager(int forward) {
        if (pagersTemp.size() < 3) {
            loadForwardChapter();
        }
        return pagersTemp.get(forward).getContent();
    }

    /**
     * @author xf
     * @time 2018/8/13  11:36
     * @describe 将章节分页处理
     */
    private void getPagers(String text) {
        StringBuilder builder = new StringBuilder();
        if (TextUtils.isEmpty(text))
            return;
        String[] lines = text.split("\n");
        for (int n = 0; n < lines.length; n++) {
            String line = lines[n];
            int dp = line.length() % wordCount;
            int lineCount = line.length() / wordCount;//计算按一个换行符截取的字符串多少行能显示
            if (dp != 0)
                lineCount += 1;
            if (contentHeight < mInterval + bottomMargin) {//当到底部是跳出循环
                break;
            }
            if (lineCount == 1) {//当只只有一行的时候
                contentHeight -= mInterval;
                if (contentHeight < mInterval + bottomMargin) {//当到底部是跳出循环
                    break;
                }
                LogUtils.d(line);
                builder.append(line + "\n");
                tempPagerCount += line.length();
            } else {
                for (int m = 0; m < lineCount; m++) {
                    if (contentHeight < mInterval + bottomMargin) {//当到底部是跳出循环，并计算剩余字符
                        break;
                    }
                    contentHeight -= mInterval;
                    if (m == lineCount - 1 && m > 0) {//当到最后一行的时候,
                        int start = m * wordCount;
                        String s = line.substring(start, line.length());
                        tempPagerCount += s.length();
                        LogUtils.d("else if>>>" + s);
                        builder.append(s + "\n");
                    } else {
                        String s = line.substring(m * wordCount, wordCount * m + wordCount);
                        tempPagerCount += s.length();
                        LogUtils.d("else else>>>" + s);
                        builder.append(s + "\n");
                    }
                }
            }
            lineSpn++;
        }
        Pager pager = new Pager();
        pager.setContent(builder.toString());

        if (isNext) {
            if (pagers.size() > 5) {
                pagers.remove(0);
            }
            pagers.add(pager);
        }
        if (pagersTemp.size() > 5) {
            pagersTemp.remove(0);
        }
        pagersTemp.add(pager);
        contentHeight = (int) mVisibleHeight;
        if (tempPagerCount + lineSpn < 1) {
            text = text.substring(tempPagerCount + lineSpn);
        } else
            text = "";
        LogUtils.d(lineSpn + ">>>>>>lineSpn");
        lineSpn = 0;
        tempPagerCount = 0;
        LogUtils.d("mTextContent=" + text);
        getPagers(text);
    }
}
